package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 再来一单
     * @param id
     */
    public void repetitionOrder(Long id) {

        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetail(id);

        //当前用户id
        Long userId = BaseContext.getCurrentId();

        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(x,shoppingCart,"id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult getHistoryOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //获取当前登录用户id
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> page = orderMapper.getHistoryOrders(ordersPageQueryDTO);

        //封装返回结果
        List<OrderVO> orderVOList = new ArrayList<>();

        addOrderDetails(page,orderVOList);

        long total = page.getTotal();

        return new PageResult(total,orderVOList);
    }

    /**
     * 补充订单详情字段
     * @param page
     * @param orderVOList
     */
    public void addOrderDetails(Page<Orders> page, List<OrderVO> orderVOList){
        for (Orders orders : page) {
           List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetail(orders.getId());

           OrderVO orderVO = new OrderVO();
           BeanUtils.copyProperties(orders,orderVO);
           orderVO.setOrderDetailList(orderDetailList);
            //根据订单详情生成otherDishes字符串,并封装到orderVO中
            String otherDishes = getOtherDishes(orderDetailList);
            orderVO.setOrderDishes(otherDishes);
            orderVOList.add(orderVO);
        }
    }

    /**
     * 根据订单详情生成otherDishes字符串
     * @param orderDetailList
     * @return
     */
    private String getOtherDishes(List<OrderDetail> orderDetailList) {
        //根据订单详情生成otherDishes字符串
        List<String> otherDishesList = orderDetailList.stream().map(orderDetail -> orderDetail.getName() + "*" + orderDetail.getNumber()).collect(Collectors.toList());
        return String.join(";", otherDishesList);
    }

    /**
     * 取消订单
     * @param id
     */
    public void cancelOrder(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.CANCELLED)
                .build();
        //TODO 取消订单后不确定是否需要删除取消订单的数据
        orderMapper.cancelOrder(orders);
    }

    /**
     * 查看订单详情
     * @param orderId
     * @return
     */
    public OrderVO getOrderDetail(Long orderId) {

        //根据订单id查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetail(orderId);
        //查询该订单信息
        Orders order = orderMapper.getById(orderId);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //处理各种业务异常（地址簿为空，购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null){
            // 抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 查询当前用户购物车数据
        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart
                .builder()
                .userId(currentId)
                .build();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        if(shoppingCarts == null || shoppingCarts.size() == 0){
            // 抛出业务异常
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(currentId);
        orders.setAddress(addressBook.getProvinceName() + "::" + addressBook.getCityName() + "::" + addressBook.getDistrictName());

        orderMapper.insert(orders);

        List<OrderDetail> orderDetailList = new ArrayList<>();
        //向订单明细表插入n条数据
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());// 设置当前订单明细关联的订单id
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        //清空购物车数据
        shoppingCartMapper.cleanShoppingCart(currentId);

        //封装VO返回结果
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
    }

    /**
     * 客户催单
     * @param id
     */
    public void reminder(Long id) {

        Orders orders = orderMapper.getById(id);

        /*订单不存在，抛出业务异常*/
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Map map = new HashMap();
        map.put("type",2);//1.表示来单提醒，2.表示客户催单
        map.put("orderId",id);
        map.put("content","订单号：" + orders.getNumber());

        //通过websocket向管理端推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 管理端订单取消
     * @param ordersCancelDTO
     */
    public void cancelOrderAdmin(OrdersCancelDTO ordersCancelDTO) {
        orderMapper.cancelOrderAdmin(ordersCancelDTO);
    }

    /**
     * 各个状态的订单数量统计
     */
    public OrderStatisticsVO getStatistics() {
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        //待派送数量
        Integer confirmed = orderMapper.getConfirmed(Orders.CONFIRMED);

        //派送中数量
        Integer deliveryInProgress = orderMapper.getDeliveryInProgress(Orders.DELIVERY_IN_PROGRESS);

        //待接单数量
        Integer toBeConfirmed = orderMapper.getToBeConfirmed(Orders.TO_BE_CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        
        return orderStatisticsVO;
    }

    /**
     * 完成订单
     * @param orderId
     */
    public void completeOrder(Long orderId) {

        Orders orders = Orders.builder()
                .id(orderId)
                .status(Orders.COMPLETED)
                .build();
        orderMapper.completeOrder(orders);
    }



    /**
     * 派送订单
     * @param orderId
     */
    public void doDelivery(Long orderId) {
        Orders orders = Orders.builder()
                .status(Orders.DELIVERY_IN_PROGRESS)
                .id(orderId)
                .build();
        orderMapper.doDelivery(orders);
    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     */
    public PageResult conditionSearchOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.conditionSearchOrders(ordersPageQueryDTO);

        List<Orders> result = page.getResult();

        long total = page.getTotal();

        return new PageResult(total,result);
    }



    /**
     * 抽取区间所有日期方法
     * @param begin
     * @param end
     * @return
     */
    public List<LocalDate> getDate(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
